import React from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';

import _ from 'lodash';

import { Form } from '@ant-design/compatible';
import PageHeader from '@/components/PageHeader';
import { FormComponentProps } from '@ant-design/compatible/es/form';
import '@ant-design/compatible/assets/index.css';

import {
  Card,
  Descriptions,
  message,
  Button,
} from 'antd';

import {
  ZoomOutOutlined,
  ZoomInOutlined,
  CloseCircleOutlined,
  UndoOutlined,
  DownloadOutlined,
} from '@ant-design/icons';

import styles from '../../delivery/detail/index.less';

const { Item } = Descriptions;

interface TableListProps extends FormComponentProps {
  dispatch: Dispatch<any>;
  logisCenterWithdrawDetail: any;
  INITINFO: any;
  match: { params: { bid: number } },
}

interface TableListState{
  imgSize:number;
  imgRotate:number;
}
/* eslint react/no-multi-comp:0 */
@connect(({ logisCenterWithdrawDetail, common: { INITINFO } }: any) => ({
  logisCenterWithdrawDetail,
  INITINFO,
}))
class TableList extends React.Component<TableListProps, TableListState> {
  state:TableListState = {
    imgSize: 1,
    imgRotate: 0,
  }

  componentDidMount() {
    const { match: { params: { bid = 0 } } } = this.props;
    if (bid) {
      const { dispatch } = this.props;
      dispatch({
        type: 'logisCenterWithdrawDetail/fetch',
        payload: { orderId: bid },
      });
    } else {
      message.warning('订单不存在');
    }
  }


  // 关闭
  handleCloseImg = (id: any) => {
    const div: any = document.getElementById(`imgContent${id}`);
    const img: any = document.getElementById(`img${id}`);

    div.style.display = 'none';
    img.style.left = '';
    img.style.top = '';
    img.style.transform = 'scale3d(1,1,1) rotate(0deg)';
    this.setState({ imgSize: 1, imgRotate: 0 });
  }


  // 放大和缩小
  handleChangeImgSize = (size: number, id: any) => {
    const { imgSize, imgRotate } = this.state;
    const middleImageSize = imgSize + size;
    const new_imgSize = middleImageSize < 0.5 ? imgSize : middleImageSize;

    this.commonFun(new_imgSize, imgRotate, id);
  }

  // 拖拽图片
  mousedownImage = (e: any, id: any) => {
    const event = e || window.event;
    const target = event.target || event.srcElement;
    const disX = event.clientX - target.offsetLeft;
    const disY = event.clientY - target.offsetTop;
    const p: any = document.getElementById(`imgText${id}`);
    p.style.display = 'none';

    document.onmousemove = (ev: any) => {
      ev.preventDefault();
      const events = ev || window.event;
      const img: any = document.getElementById(`img${id}`);
      const needX = events.clientX - disX;
      const needY = events.clientY - disY;
      img.style.left = `${needX}px`;
      img.style.top = `${needY}px`;
    };

    document.onmouseup = () => {
      document.onmousemove = null;
      document.onmouseup = null;
    };
  }


  // 下载图片
  handleDownImage = (imgSrc: any) => {
    const canvas: any = document.createElement('canvas');
    const img = document.createElement('img');
    img.onload = (e) => {
      canvas.width = img.width;
      canvas.height = img.height;
      const context = canvas.getContext('2d');
      context?.drawImage(img, 0, 0, img.width, img.height);
      canvas.getContext('2d').drawImage(img, 0, 0, img.width, img.height);
      canvas.toBlob((blob: any) => {
        const link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        link.download = '';
        link.click();
      }, 'image/jpeg');
    };
    img.setAttribute('crossOrigin', '*');
    img.src = imgSrc;
  }

  // 点击面单图片
  handleExpress = (e: any, remark: any, id: any) => {
    const divs: any = document.getElementsByClassName('imgContent');
    const div: any = document.getElementById(`imgContent${id}`);

    Array.prototype.forEach.call(divs, (element: any) => {
      element.style.display = 'none';
      const img = element.getElementsByTagName('img')[0];
      img.style.transform = 'scale3d(1,1,1) rotate(0deg)';
    });

    div.style.display = 'block';
    this.setState({ imgSize: 1, imgRotate: 0 });
  }

  // 旋转
  handleRotating = (id: any) => {
    const { imgSize, imgRotate } = this.state;
    const new_imgRotate = imgRotate - 90;

    this.commonFun(imgSize, new_imgRotate, id);
  }

  commonFun = (imgSize: any, imgRotate: any, id: any) => {
    const img: any = document.getElementById(`img${id}`);
    img.style.transform = `scale3d(${imgSize},${imgSize},1) rotate(${imgRotate}deg)`;

    this.setState({ imgSize, imgRotate });
  }

  render() {
    const {
      logisCenterWithdrawDetail: {
        detailInfo: { orderInfo = {}, operLogInfo = [] },
      },
    } = this.props;

    const weekArr = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];

    return (
      <>
        <PageHeader />
        <Card bordered={false} title="订单信息">
          <Descriptions className="marginB12">
            <Item label="订单编号">{orderInfo.expCode}</Item>
            <Item label="订单批次">{orderInfo.batchName}</Item>
            <Item label="订单状态">{orderInfo.statusName}</Item>
          </Descriptions>
          <Descriptions bordered size="small">
            <Descriptions.Item label="　　运单号">{orderInfo.expCode}</Descriptions.Item>
            <Descriptions.Item label="　快递公司">{orderInfo.expressName}</Descriptions.Item>
            <Descriptions.Item label="收件人手机">{orderInfo.consigneePhone || '--'}</Descriptions.Item>
            <Descriptions.Item label="　入库时间">{orderInfo.inTime}</Descriptions.Item>
            <Descriptions.Item label="　出库时间">{orderInfo.outTime}</Descriptions.Item>
            <Descriptions.Item label="　存储类型">{orderInfo.storageTypeName}</Descriptions.Item>
            <Descriptions.Item label="　　取件码">{orderInfo.openCode}</Descriptions.Item>
            <Descriptions.Item label="　存储位置">{orderInfo.address}</Descriptions.Item>
            <Descriptions.Item label="　退回快照">{orderInfo.withdrawPhoto || '--'}</Descriptions.Item>
          </Descriptions>
        </Card>
        <Card bordered={false} title="操作信息">
          {(operLogInfo || []).map((log: any) => {
            const reg = /(https|http|img).+/;
            const { remark, id } = log;
            const imgTrue = remark.includes('img:');
            let remakeContent;

            if (reg.test(remark)) {
              remakeContent = (
                <div
                  className="ocrImg"
                  style={{ flex: 1 }}
                >
                  <span onClick={(e) => this.handleExpress(e, remark, id)}>
                    {imgTrue ? remark.split('img:')[0] : 'OCR面单图片'}
                  </span>
                  <div
                    id={`imgContent${id}`}
                    className="imgContent"
                    style={{
                      position: 'absolute',
                      top: '0',
                      right: '10%',
                      width: '500px',
                      height: '600px',
                      zIndex: 100,
                      display: 'none',
                    }}
                  >
                    <CloseCircleOutlined
                      className={styles.closeCircle}
                      onClick={() => this.handleCloseImg(id)}
                    />
                    <div className={styles.checkImg}>
                      <p className={styles.imgText} id={`imgText${id}`}>图片加载中，请稍后...</p>
                      {/* eslint-disable-next-line jsx-a11y/no-noninteractive-element-interactions */}
                      <img
                        id={`img${id}`}
                        className="img"
                        src={imgTrue ? remark.split('img:')[1] : remark}
                        alt=""
                        onMouseDown={(e) => this.mousedownImage(e, id)}
                        style={{
                          position: 'absolute',
                          height: '500px',
                          transition: '0.5s',
                          zIndex: 101,
                          cursor: 'move',
                        }}
                      />
                    </div>
                    <div className="marginT20">
                      <Button
                        type="primary"
                        icon={<ZoomInOutlined />}
                        className="marginR16"
                        onClick={() => this.handleChangeImgSize(imgTrue ? 0.5 : 0.2, id)}
                      >
                        放大
                      </Button>
                      <Button
                        type="primary"
                        icon={<ZoomOutOutlined />}
                        className="marginR16"
                        danger
                        onClick={() => this.handleChangeImgSize(imgTrue ? -0.5 : -0.2, id)}
                      >
                        缩小
                      </Button>
                      <Button
                        type="primary"
                        icon={<UndoOutlined />}
                        className="marginR16"
                        onClick={() => this.handleRotating(id)}
                      >
                        旋转
                      </Button>
                      <Button
                        type="primary"
                        icon={<DownloadOutlined />}
                        onClick={() => this.handleDownImage(imgTrue ? remark.split('img:')[1] : remark)}
                      >
                        下载
                      </Button>
                    </div>
                  </div>
                </div>
              );
            } else {
              remakeContent = remark;
            }
            return (
              <div
                key={log.id}
                className="marginB8"
                style={{ display: 'flex', lineHeight: '30px', padding: '0 24px' }}
              >
                <span>({weekArr[new Date(log.createTime.split(' ')[0]).getDay()]}) {log.createTime}：
                </span>
                {remakeContent}
              </div>
            );
          })}
        </Card>
      </>
    );
  }
}

export default Form.create<TableListProps>()(TableList);
